package part23swingdemo.com.etc.ui;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import part23swingdemo.com.etc.pojo.Userinfo;
import part23swingdemo.com.etc.service.UserinfoService;
import part23swingdemo.com.etc.service.UserinfoServiceImpl;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;

public class LoginJFrame {

	private JFrame frame;
	private JTextField text_username;
	private JLabel lblNewLabel;
	private JPasswordField password;
	
	private UserinfoService userinfoService = new UserinfoServiceImpl();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LoginJFrame window = new LoginJFrame();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public LoginJFrame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		//窗口显示在页面中间
		frame.setLocationRelativeTo(null);
		//窗口不允许调整大小
		frame.setResizable(false);
		//设置窗口名称
		frame.setTitle("登录页面");
		
		JLabel label = new JLabel("用户名：");
		label.setBounds(66, 60, 56, 36);
		frame.getContentPane().add(label);
		
		text_username = new JTextField();
		text_username.setBounds(132, 66, 200, 26);
		frame.getContentPane().add(text_username);
		text_username.setColumns(10);
		
		lblNewLabel = new JLabel("密码：");
		lblNewLabel.setBounds(69, 116, 65, 50);
		frame.getContentPane().add(lblNewLabel);
		
		JButton btn_login = new JButton("登录");
		btn_login.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 1获取用户名
				String username = text_username.getText().trim();
				// 2获取密码
				char[] p = password.getPassword();
				// 将字符数组转成字符串
				String password = new String(p);
				// 3调用登录业务
				Userinfo userinfo = userinfoService.login(username, password);
				if (userinfo != null) {
					// 登录成功
					JOptionPane.showMessageDialog(null, "登录成功");
					// 1 打开新一个新界面--主界面，并且传递参数
					MainJFrame window = new MainJFrame(userinfo);
					// 2 当前界面隐藏或者销毁
//					frame.setVisible(false);
					frame.dispose();
				}else {
					JOptionPane.showMessageDialog(null, "登录失败,用户名或密码错误");
				}
			}
		});
		btn_login.setBounds(158, 193, 93, 23);
		frame.getContentPane().add(btn_login);
		
		password = new JPasswordField();
		password.setBounds(132, 131, 200, 21);
		frame.getContentPane().add(password);
		// 将界面做显示
		frame.setVisible(true);
	}
}
